<?php
function getIconAppUrl(){
	$icon_url = 'http://'.$_SERVER['HTTP_HOST'].__ROOT__ . '/apps/weiba/Appinfo/icon_app_small.png';
	return $icon_url;
}


/**
 * 保存上传文件信息到附件表
 *
 * @param string $attach_type   附件类型
 * @param array  $upload_info 	上传文件信息
 * Create Data <2013-05-02>
 */
function addAttach($attach_type = 'weiba_logo', $upload_info) {
	$attach = M('Attach'); //实例化Attach模型
	foreach ($upload_info as $u) {
		$map['attach_type'] = $attach_type;
		$map['userId'] = 1;
		$map['name'] = $u['name'];
		$map['type'] = $u['type'];
		$map['size'] = $u['size'];
		$map['extension'] = strtolower($u['extension']);
		$map['hash'] = $u['hash'];
		$map['savepath'] = $u['savepath'];
		$map['savename'] = $u['savename'];
		$map['uploadTime'] = time();
		$aid = $attach->add($map);
		$map['id'] = intval($aid);
		$map['key'] = $u['key'];
		unset ($map);
	}
	return $aid;
}

/**
 * 微吧获取图片存在相对地址
 * @param integer $attachid 附件ID
 * @return string 附件存储相对地址
 */
function getImageUrlByAttachIdByWeiba ($attachid) {
    if ($attachInfo = model('Attach')->getAttachById($attachid)) {
        return __ROOT__.'/data/uploads/'.$attachInfo['savepath'].$attachInfo['savename'];
    } else {
        return false;
    }
}

/**
 * 根据存储路径，获取图片真实URL
 */
function getPhotoUrl($savepath) {
	return './data/uploads/'.$savepath;
}

/**
 * 去除标签，截取blog的长度
 * @param mixed $content 
 * @param mixed $length 
 * @access public
 * @return void
 */
function getBlogShort($content,$length = 40) {
	$content	=	stripslashes($content);
	$content	=	strip_tags($content);
	$content	=	getShort($content,$length);
	return $content;
}

/**
 * 获取用户姓名
 * @param unknown_type $uid
 * @param unknown_type $lang
 */
function getUserName($uid,$lang='zh') {
	global $yl;
	if ($uid == $yl['user']['uid'] || $uid == $yl['user']['uname'])
		return $yl['user']['uname'];

	static $_MapName = array();
	if(!isset($_MapName[$uid])){
		if(is_numeric($uid)){
			$userinfo = model('User')->getUserByIdentifier($uid, 'uid');
		}else{
			$userinfo = model('User')->getUserByIdentifier($uid, 'uname');
		}
		$_MapName[$uid] = $userinfo['uname'];
	}
	return htmlspecialchars($_MapName[$uid]);
}

/**
 * 友好的时间显示
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 */
function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
	//sTime=源时间，cTime=当前时间，dTime=时间差
	$cTime		=	time();
	$dTime		=	$cTime - $sTime;
	$dDay		=	intval(date("z",$cTime)) - intval(date("z",$sTime));
	//$dDay		=	intval($dTime/3600/24);
	$dYear		=	intval(date("Y",$cTime)) - intval(date("Y",$sTime));
	//normal：n秒前，n分钟前，n小时前，日期
	if($type=='normal'){
		if( $dTime < 60 ){
			return $dTime."秒前";
		}elseif( $dTime < 3600 ){
			return intval($dTime/60)."分钟前";
			//今天的数据.年份相同.日期相同.
		}elseif( $dYear==0 && $dDay == 0  ){
			//return intval($dTime/3600)."小时前";
			return '今天'.date('H:i',$sTime);
		}elseif($dYear==0){
			return date("m月d日 H:i",$sTime);
		}else{
			return date("Y-m-d H:i",$sTime);
		}
	}elseif($type=='mohu'){
		if( $dTime < 60 ){
			return $dTime."秒前";
		}elseif( $dTime < 3600 ){
			return intval($dTime/60)."分钟前";
		}elseif( $dTime >= 3600 && $dDay == 0  ){
			return intval($dTime/3600)."小时前";
		}elseif( $dDay > 0 && $dDay<=7 ){
			return intval($dDay)."天前";
		}elseif( $dDay > 7 &&  $dDay <= 30 ){
			return intval($dDay/7) . '周前';
		}elseif( $dDay > 30 ){
			return intval($dDay/30) . '个月前';
		}
		//full: Y-m-d , H:i:s
	}elseif($type=='full'){
		return date("Y-m-d , H:i:s",$sTime);
	}elseif($type=='ymd'){
		return date("Y-m-d",$sTime);
	}else{
		if( $dTime < 60 ){
			return $dTime."秒前";
		}elseif( $dTime < 3600 ){
			return intval($dTime/60)."分钟前";
		}elseif( $dTime >= 3600 && $dDay == 0  ){
			return intval($dTime/3600)."小时前";
		}elseif($dYear==0){
			return date("Y-m-d H:i:s",$sTime);
		}else{
			return date("Y-m-d H:i:s",$sTime);
		}
	}
}

/**
 * 获取字符字节长度
 * @param unknown_type $str
 * @param unknown_type $length
 * @param unknown_type $ext
 * @return unknown
 */
function getShort($str, $length = 40, $ext = '') {
	$str	=	htmlspecialchars($str);
	$str	=	strip_tags($str);
	$str	=	htmlspecialchars_decode($str);
	$strlenth	=	0;
	$out		=	'';
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/", $str, $match);
	foreach($match[0] as $v){
		preg_match("/[\xe0-\xef][\x80-\xbf]{2}/",$v, $matchs);
		if(!empty($matchs[0])){
			$strlenth	+=	1;
		}elseif(is_numeric($v)){
			$strlenth	+=	0.5;    // 字符字节长度比例 汉字为1
		}else{
			$strlenth	+=	0.5;    // 字符字节长度比例 汉字为1
		}

		if ($strlenth > $length) {
			$output .= $ext;
			break;
		}

		$output	.=	$v;
	}
	return $output;
}

/**
 * 返回解析的空间地址
 * @param unknown_type $uid
 * @param unknown_type $class
 * @param unknown_type $target
 * @param unknown_type $text
 * @param unknown_type $icon
 * @return string
 */
function getUserSpace($uid, $class, $target, $text, $icon) {
	static $_userinfo = array ();
	if (!isset ($_userinfo[$uid])) {
		$_userinfo[$uid] = model('User')->getUserByIdentifier($uid, 'uid');
	}
	$target = ($target) ? $target : '_self';
	$text = ($text) ? $text : $_userinfo[$uid]['uname'];

	if ($icon) {
		//$user_name_end = '<img src='.$icon.' event-node="face_card" uid="'.$uid.'"/>';
		$user_name_end = $icon;
	}else{
		$user_name_end =$_userinfo[$uid]['uname'] ;
	}

	if ($_userinfo[$uid]['domain']){
// 		$url = URL('home/Space/index', array (
// 				'uid' => $_userinfo[$uid]['domain']
// 		));
		$url='http://www.i8i8i8.com/space/'.$_userinfo[$uid]['domain'].'.html';
	}
	else{
// 		$url = URL('home/Space/index', array (
// 				'uid' => $uid
// 		));
		$url='http://www.i8i8i8.com/space/'.$uid.'.html';
	}

	$user_space_info = "<a href='{$url}' class='{$class}' target='{$target}'> ".$user_name_end . "</a>";
	return $user_space_info;
}

/**
 * 获取用户头像
 * M2
 * @param int $uid 用户ID
 * @param string $size 头像大小 m:中图 | s:小图 | 其它:大图
 * @return string 头像的URL地址
 */
function getUserFace($uid, $size, $width=66, $height=66) {
	$size = ($size) ? $size : 'm';
	if ($size == 'm') {
		$type = 'middle';
	}
	elseif ($size == 's') {
		$type = 'small';
		$width = 42;
		$height=42;
	} else {
		$type = 'big';
	}
	$uid_to_path = common('Url')->convertUidToPath($uid);
	$userface = './data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
	
	if (is_file($userface)) {
		$face = __ROOT__.'/data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
	} else {
		$userface = './data/uploads/avatar/0/' . $type . '.jpg';
		$face = __ROOT__.'/data/uploads/avatar/0/'.$type.'.jpg';
	}
	return "<img src=" . $face .'?'.filemtime($userface). " width='".$width."' height='".$height."'>";
}

/**
 * 获取关注状态
 * @param int $uid 用户ID
 * @param int $fid 好友ID
 * @param int $type 0:关注好友 1:关注话题
 * @return string eachfollow:相互关注 | havefollow:已关注 | unfollow:未关注 | 空:同一个用户
 */
function getFollowState($uid,$fid,$type=0) {

	if ($uid <= 0 || $fid <= 0)
		return 'unfollow';

	if ($type == 0) {
		if ($uid==$fid)
			return 'unfollow';

		if (M('weibo_follow')->where("(uid=$uid AND fid=$fid AND type=0) OR (uid=$fid AND fid=$uid AND type=0)")->count() == 2) {
			return 'eachfollow';
		}else if ( M('weibo_follow')->where("uid=$uid AND fid=$fid AND type=0")->count()) {
			return 'havefollow';
		}else {
			return 'unfollow';
		}
	}else if($type == 1) {
		$db_prefix  = C('DB_PREFIX');
		if(is_numeric($fid)){
			$fid['topic_id'] = $fid;
		}
		$map = $fid['topic_id']?"AND a.topic_id={$fid['topic_id']}":"AND a.name='{$fid['name']}'";
		$topic = M('weibo_follow')->field('a.topic_id')
		->table("{$db_prefix}weibo_topic a LEFT JOIN {$db_prefix}weibo_follow b ON b.fid=a.topic_id")
		->where("b.uid={$uid} AND b.type=1 {$map}")
		->find();
		if($topic){
			return 'havefollow';
		}else{
			return 'unfollow';
		}
	}
}